package com.itxiuyixiu.homework.security.service;

import com.itxiuyixiu.homework.entity.dao.StudentDao;
import com.itxiuyixiu.homework.entity.model.Student;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author 黄磊
 * @date 2020/3/6
 */
@Component
public class StudentDetailsServiceImpl implements UserDetailsService {
    private final StudentDao studentDao;

    public StudentDetailsServiceImpl(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Optional<Student> studentOptional = studentDao.findById(s);
        if (studentOptional.isPresent()) {
            Student student = studentOptional.get();
            return new User(student.getStudentId(), student.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(student.getAuthorities()));
        } else {
            throw new UsernameNotFoundException("学生号为：" + s + "的学生没有被找到");
        }
    }
}
